package com.example.controller;

import com.example.delay.factory.HazelcastDelayJobFactory;
import com.example.delay.job.TestJob;
import com.example.service.HazelcastService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/*
 * @className: TestDelayJobController
 * @author: chentao
 * @date: 2025/2/20 上午11:07
 * @Version: 1.0
 * @description:
 */
@RestController
public class TestDelayJobController implements InitializingBean, DisposableBean {

    Logger logger = LoggerFactory.getLogger(getClass());

    private HazelcastDelayJobFactory hazelcastDelayJobFactory;

    @Resource
    private HazelcastService hazelcastService;

    /****
     * 设置一个延时任务
     * @param time
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "setJob")
    public String setJob(long time) throws Exception {
        return this.hazelcastDelayJobFactory.put(TestJob.class, time, TimeUnit.SECONDS);
    }

    /****
     * 取消一个延时任务
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "delJob")
    public void delJob(String id) throws Exception {
        this.hazelcastDelayJobFactory.cancel(id);
    }

    /****
     * 初始化延迟任务工厂
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        this.hazelcastDelayJobFactory = new HazelcastDelayJobFactory(getClass().getName(), hazelcastService);
        this.hazelcastDelayJobFactory.start();
    }

    /****
     * 关闭工厂回收资源
     * @throws Exception
     */
    @Override
    public void destroy() throws Exception {
        this.hazelcastDelayJobFactory.stop();
    }
}
